/**
 * 1-导入路由列表
 * 2-actions中遍历权限列表asyncRoutes,同时遍历后台返回的菜单
 * 3-如果后台的数据,在权限列表asyncRoutes能找到,就动态的添加到accessedRoutes
 * 4-将accessedRoutes暴露出去,在permission.js中接受
 * 5-通过addRoutes方法 动态添加路由表实现权限登录
 */
import { constantRoutes, asyncRoutes } from '@/router'

const state = {
  routes: [],
  addRoutes: []
}

const mutations = {
  SET_ROUTES: (state, routes) => {
    state.addRoutes = routes
    state.routes = constantRoutes.concat(routes)
  }
}

const actions = {
  generateRoutes({ commit }, permissionList) {
    return new Promise(resolve => {
      const accessedRoutes = []
      /**
       * 权限判断
       */
      asyncRoutes.forEach(asyncItem => {
        // 不使用权限判断
        // accessedRoutes.push(asyncItem)

        permissionList.forEach(permissionItem => {
          if (asyncItem.meta) {
            /**
             * 判断一级权限
             */
            if (asyncItem.path === permissionItem.url) {
              const childrenRowList = []
              for (const asyncChildrenIndex in asyncItem.children) {
                const asyncChildrenItem = asyncItem.children[asyncChildrenIndex]
                permissionItem.children.forEach(permissionItemChildren => {
                  /**
                   * 判断二级权限
                   */
                  if (asyncChildrenItem.path === permissionItemChildren.url) {
                    /**
                     * 判断三级权限
                     */
                    if (typeof asyncChildrenItem.children !== 'undefined' && asyncChildrenItem.children.length !== 0) {
                      asyncItem.children[asyncChildrenIndex].children = asyncChildrenItem.children.filter(asyncChildrenLastChildrenRow => {
                        let hasLastChildren = false
                        if (typeof permissionItemChildren.children !== 'undefined' && permissionItemChildren.children.length !== 0) {
                          permissionItemChildren.children.forEach(permissionItemLastItemChildren => {
                            if (asyncChildrenLastChildrenRow.path.includes(permissionItemLastItemChildren.url)) {
                              hasLastChildren = true
                            }
                          })
                        }
                        return hasLastChildren
                      })
                    }
                    childrenRowList.push(asyncItem.children[asyncChildrenIndex])
                  }
                })
              }
              asyncItem.children = childrenRowList
              accessedRoutes.push(asyncItem)
            }
          }
        })
      })
      commit('SET_ROUTES', accessedRoutes)
      resolve(accessedRoutes)
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

